import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Post,
  Put,
  UseInterceptors,
} from '@nestjs/common';
import { TransformInterceptor } from 'src/interceptor/intersform.interceptor';
import { createNodeDataDto } from './dto/node.dto';
import { NodeService } from './node.service';

@Controller('/node')
@UseInterceptors(new TransformInterceptor())
export class NodeController {
  constructor(private readonly nodeService: NodeService) {}

  // 获取总局节点信息
  @Get()
  async getNodeList() {
    const res = await this.nodeService.getNodeList();
    return {
      message: '获取成功',
      data: res,
    };
  }

  // 新增总局节点
  @Post()
  async createZongjuList(@Body() data: createNodeDataDto) {
    if ((await this.nodeService.getNodeInfoByName(data.node_name)).length) {
      return {
        code: 405,
        message: `${data.node_name}已经存在`,
        data: [],
      };
    } else {
      try {
        this.nodeService.createNode([data]);
        return {
          message: '添加成功',
        };
      } catch (err) {
        return {
          code: 500,
          message: err,
        };
      }
    }
  }

  // 根据id删除节点
  @Delete(':id')
  async removeLianlu(@Param('id') id: string) {
    if ((await this.nodeService.getNodeInfoById(id)).length) {
      const res = await this.nodeService.delNode(id);
      return { data: res, message: '删除成功' };
    } else {
      return {
        data: [],
        message: '该节点不存在！',
        code: 405,
      };
    }
  }
  // 更新节点信息
  @Put(':id')
  async update(@Param('id') id: string, @Body() data) {
    if ((await this.nodeService.getNodeInfoByName(data.node_name)).length) {
      return {
        code: 405,
        message: `${data.node_name}已经存在`,
        data: [],
      };
    } else {
      try {
        const res = await this.nodeService.updataNode(id, data);
        return {
          data: res,
          message: '节点信息更新成功',
        };
      } catch (err) {
        return {
          code: 500,
          message: err,
        };
      }
    }
  }
}
